/*
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.android.rest.impl;

import org.geoscheduler.android.exceptions.GSContextNotInitializedException;
import org.geoscheduler.android.exceptions.GSRestFailedException;
import org.geoscheduler.android.exceptions.GSRestReturnedErrorException;
import org.geoscheduler.android.rest.AbstractRestClient;
import org.geoscheduler.android.rest.Auth;
import org.geoscheduler.model.Account;
import org.geoscheduler.model.Token;
import org.json.JSONObject;

import android.content.Context;

/**
 * Naive implementation of {@link Auth} interface.
 * 
 * This is expected to be refactored couple times ;)
 * 
 * @author srakyi
 */
public class BasicAuth extends AbstractRestClient implements Auth {
	private static final String RES_PATH_TOKENS = "tokens";
	private static final String RES_PATH_ACCOUNTS = "accounts";

	/**
	 * Hand instantiation not expected, ask for instance from {@link Context}.
	 */
	public BasicAuth() {
		super();
	}
	
	/**
	 * @see org.geoscheduler.android.rest.Auth#register(org.geoscheduler.model.Account)
	 */
	@Override
	public Account register(Account acc) throws GSRestFailedException, GSRestReturnedErrorException, GSContextNotInitializedException {
		JSONObject jsonAcc = marshall(acc);
		
		return unmarshall(new Account(), restPostCall(RES_PATH_ACCOUNTS, jsonAcc));
	}

	/**
	 * @see org.geoscheduler.android.rest.Auth#logIn(java.lang.String, java.lang.String)
	 */
	@Override
	public Token logIn(Account acc) throws GSRestFailedException, GSRestReturnedErrorException, GSContextNotInitializedException {
		JSONObject jsonAcc = marshall(acc);
		
		Token token = unmarshall(new Token(), restPostCall(RES_PATH_TOKENS, jsonAcc));
		token.setSalt(Token.computeSalt(acc, token.getTokenId()));
		
		return token;
	}
}
